package com.fmc.passport.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class URLContent {

	public static String POST = "post";
	public static String GET = "get";

	public static InputStream getHttpConnection(String urlString, String method)
			throws Exception {
		InputStream stream = null;
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = null;
		if (method.equals(GET)) {
			HttpGet httpGet = new HttpGet(urlString);
			httpResponse = httpClient.execute(httpGet);
		} else if (method.equals(POST)) {
			HttpPost post = new HttpPost(urlString);
			httpResponse = httpClient.execute(post);
		}
		HttpEntity httpEntity = httpResponse.getEntity();
		stream = httpEntity.getContent();
		return stream;
	}

	public static Bitmap downloadImage(String url) throws Exception {
		Bitmap bitmap = null;
		InputStream stream = null;
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inSampleSize = 1;

		try {
			stream = getHttpConnection(url, URLContent.GET);
			bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
		return bitmap;
	}

	public static String getContent(String url) throws Exception {
		String result = null;
		BufferedReader br = null;
		try {
			InputStream is = URLContent.getHttpConnection(url, URLContent.GET);
			br = new BufferedReader(new InputStreamReader(is));
			String inputLine;
			result = "";
			while ((inputLine = br.readLine()) != null) {
				result += inputLine + "\r\n";
			}
		} finally {
			br.close();

		}
		return result.trim();
	}
}
